package com.own.component.util.excel.util.write.record;

import com.own.component.util.excel.exception.ExcelException;
import com.own.component.util.excel.util.write.method.BaseCoordinateMethod;
import com.own.component.util.excel.util.write.method.BaseCssMethod;
import com.own.component.util.excel.util.write.method.BaseExcelMethod;
import com.own.component.util.excel.util.write.method.BaseFreezeMethod;
import com.own.component.util.excel.util.write.method.BaseHeightMethod;
import com.own.component.util.excel.util.write.method.BaseMergeMethod;
import com.own.component.util.excel.util.write.method.BaseSheetMethod;
import com.own.component.util.excel.util.write.method.BaseStyleMethod;
import com.own.component.util.excel.util.write.method.BaseValueMethod;
import com.own.component.util.excel.util.write.method.BaseWidthMethod;
import com.own.component.util.excel.util.write.model.Style;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ExcelRecord
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
@Slf4j
public class ExcelRecord implements
        BaseExcelMethod,
        BaseFreezeMethod,
        BaseHeightMethod,
        BaseMergeMethod,
        BaseCoordinateMethod,
        BaseSheetMethod,
        BaseStyleMethod,
        BaseValueMethod,
        BaseWidthMethod,
        BaseCssMethod {

    /**
     * 表格列表
     */
    @Getter
    private final List<SheetRecord> sheetList;
    /**
     * 活动的sheet索引
     */
    @Setter
    @Getter
    private int sheetIndex;
    /**
     * 文件名称
     */
    @Getter
    @Setter
    private String fileName;

    public ExcelRecord() {
        this("Excel文件", true);
    }

    /**
     * 文件名称构造
     *
     * @param fileName 文件名称
     * @param addSheet 是否创建工作簿
     */
    public ExcelRecord(String fileName, boolean addSheet) {
        this.sheetList = new ArrayList<>();
        this.fileName = fileName;
        if (addSheet) {
            addSheet(fileName);
        }
    }

    /**
     * 获取当前活动的sheet
     *
     * @return 当前活动的sheet
     */
    @Override
    public SheetRecord sheet() {
        if (sheetIndex >= sheetList.size()) {
            throw new ExcelException("当前活动的sheet索引超出范围");
        }
        return sheetList.get(sheetIndex);
    }

    /**
     * 当前活动的excel
     *
     * @return 当前活动的excel
     */
    @Override
    public ExcelRecord excel() {
        return this;
    }

    /**
     * 获取样式列表
     *
     * @return 样式列表信息
     */
    public Set<Style> getStyleList() {
        return this.sheetList.stream().flatMap(sheet -> sheet.getList()
                .stream()
                .filter(Objects::nonNull)
                .map(CellRecord::getStyle)
                .filter(Objects::nonNull)
        ).collect(Collectors.toSet());
    }

}
